package com.ht.interfaces.controller;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.UUID;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.view.RedirectView;

import com.ht.api.db.bean.AjaxResult;
import com.ht.api.db.remote.ApiUtil;
import com.ht.api.db.util.RedisUtil;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * 测试
 * @author asq
 * @createTime 2024年12月21日 20:21:44
 */
@Controller
@Slf4j
public class TestController {

	@GetMapping("/geturl")
	public String getHost(@RequestHeader("Host") String host, @RequestBody JSONObject param) {
		log.info("收到请求，随机数：{}", new Random().nextFloat());

		log.info("host " + host);

		log.info(param.toStringPretty());

		return "test";
	}

	@GetMapping("/gethost")
	public AjaxResult getHost(@RequestHeader("Host") String host, @RequestParam Map<String, Object> param) {
		log.info("收到请求，随机数：{}", new Random().nextFloat());

		log.info("host " + host);

		log.info(param.toString());

		return AjaxResult.success();
	}

	// 网页授权链接
	@GetMapping("/test2")
	public RedirectView testForm(Model model) {
		log.info("收到请求，随机数：{}", new Random().nextFloat());

		String url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=ww669ca452439131bc&redirect_uri=http%3A%2F%2Fv.h5.htiannet.net%2Finterface%2Fredirect&response_type=code&scope=snsapi_base&state=123&agentid=1000008#wechat_redirect";
		RedirectView redirectView = new RedirectView();
		redirectView.setUrl(url); // 目标URL
		return redirectView;
	}

	// 侧边栏功能测试
	@GetMapping("/test")
	public String testForm2(Model model) {
		Map<String, String> corpJsConfig = getCorpJsConfig("http://m.htiannet.com/test");
		Map<String, String> jsConfig = getJsConfig("http://m.htiannet.com/test");
		model.addAttribute("configCorp", corpJsConfig);
		model.addAttribute("config", jsConfig);
		log.info("configCorp:{}", JSONUtil.toJsonPrettyStr(corpJsConfig));
		log.info("config:{}", JSONUtil.toJsonPrettyStr(jsConfig));
		return "test";
	}

	/**
	 * 获取企业的JS-SDK配置
	 */
	public Map<String, String> getCorpJsConfig(String url) {
		String jsapiTicket = getCorpJsapiTicket();
		String nonceStr = UUID.randomUUID().toString().replaceAll("-", "");
		String timestamp = String.valueOf(System.currentTimeMillis() / 1000);

		// 生成签名
		String signature = generateSignature(jsapiTicket, nonceStr, timestamp, url);

		Map<String, String> config = new HashMap<>();
		config.put("timestamp", timestamp);
		config.put("nonceStr", nonceStr);
		config.put("signature", signature);

		return config;
	}
	
	/**
	 * 获取应用的JS-SDK配置
	 */
	public Map<String, String> getJsConfig(String url) {
		String jsapiTicket = getJsapiTicket();
		String nonceStr = UUID.randomUUID().toString().replaceAll("-", "");
		String timestamp = String.valueOf(System.currentTimeMillis() / 1000);
		
		// 生成签名
		String signature = generateSignature(jsapiTicket, nonceStr, timestamp, url);
		
		Map<String, String> config = new HashMap<>();
		config.put("appId", "ww669ca452439131bc");
		config.put("timestamp", timestamp);
		config.put("nonceStr", nonceStr);
		config.put("signature", signature);
		
		return config;
	}

	/**
	 * 生成签名
	 */
	private String generateSignature(String jsapiTicket, String nonceStr, String timestamp, String url) {
		// 去除 URL 中的 # 及其后面部分
		String pureUrl = url;
		int hashIndex = url.indexOf('#');
		if (hashIndex > 0) {
			pureUrl = url.substring(0, hashIndex);
		}

		// 按照固定格式拼接字符串
		String string1 = String.format("jsapi_ticket=%s&noncestr=%s&timestamp=%s&url=%s", jsapiTicket, nonceStr,
				timestamp, pureUrl);

		// SHA1 加密
		try {
			MessageDigest digest = MessageDigest.getInstance("SHA-1");
			byte[] bytes = digest.digest(string1.getBytes(StandardCharsets.UTF_8));

			// 转换为十六进制字符串
			StringBuilder signature = new StringBuilder();
			for (byte b : bytes) {
				signature.append(String.format("%02x", b));
			}

			return signature.toString();
		} catch (NoSuchAlgorithmException e) {
			log.error("Generate signature failed", e);
			throw new RuntimeException("Generate signature failed", e);
		}
	}

	/**
	 * 获取企业的JsapiTicket
	 * @return
	 */
	private String getCorpJsapiTicket() {
		String jsapiTicket = RedisUtil.get("jsapiCorpTicket");
		if (jsapiTicket == null) {
			log.info("[jsapiTicket]redis中jsapiTicket已过期，调用微信接口获取...");
			String url = String.format(
					"https://qyapi.weixin.qq.com/cgi-bin/get_jsapi_ticket?access_token=%s",
					getToken());
			String result = ApiUtil.get(url);
			JSONObject json = JSONUtil.parseObj(result);
			jsapiTicket = json.getStr("ticket");

			RedisUtil.set("jsapiCorpTicket", jsapiTicket, 7000);

			return jsapiTicket;
		} else {
			log.info("[jsapiTicket]redis中jsapiTicket未过期，直接返回");
			return jsapiTicket;
		}

	}

	/**
	 * 获取JsapiTicket
	 * @return
	 */
	private String getJsapiTicket() {
		String jsapiTicket = RedisUtil.get("jsapiTicket");
		if (jsapiTicket == null) {
			log.info("[jsapiTicket]redis中jsapiTicket已过期，调用微信接口获取...");
			String url = String.format(
					"https://qyapi.weixin.qq.com/cgi-bin/ticket/get?access_token=%s&type=agent_config",
					getToken());
			String result = ApiUtil.get(url);
			JSONObject json = JSONUtil.parseObj(result);
			jsapiTicket = json.getStr("ticket");

			RedisUtil.set("jsapiTicket", jsapiTicket, 7000);

			return jsapiTicket;
		} else {
			log.info("[jsapiTicket]redis中jsapiTicket未过期，直接返回");
			return jsapiTicket;
		}

	}

	/**
	 * 获取指定平台及应用的access_token
	 * @param platformId 平台ID
	 * @param appId      应用ID
	 * @return
	 */
	private String getToken() {
		// 生成缓存key
		String cacheKey = String.format("token:%s:%s", "1868916871932284928", "1876990838014349312");

		// 获取缓存值
		return RedisUtil.get(cacheKey);
	}
}
